package com.ruoyi.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.domain.ParkingOrder;
import com.ruoyi.domain.ParkingRecordGate;
import com.ruoyi.domain.ParkingRecordIn;
import com.ruoyi.mapper.ParkingOrderMapper;
import com.ruoyi.mapper.ParkingRecordGateMapper;
import com.ruoyi.mapper.ParkingRecordInMapper;
import com.ruoyi.service.IParkingRecordInService;
import com.ruoyi.wss.WebSocketMessageService;
import com.ruoyi.wss.dahua.Enum.MasWebsocketEnum;
import com.ruoyi.wss.dahua.request.*;
import com.ruoyi.wss.dahua.response.ScanInOutCodeResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

import static com.ruoyi.common.utils.SecurityUtils.getUsername;

/**
 * 车辆进场记录Service业务层处理
 * 
 * @author dongdong
 * @date 2025-08-23
 */
@Slf4j
@Service
public class ParkingRecordInServiceImpl implements IParkingRecordInService 
{
    @Resource
    private ParkingRecordInMapper parkingRecordInMapper;
    @Resource
    private ParkingOrderMapper parkingOrderMapper;
    @Resource
    private ParkingRecordGateMapper parkingRecordGateMapper;
    @Autowired
    private WebSocketMessageService webSocketMessageService;


    /**
     * 查询车辆进场记录
     * 
     * @param id 车辆进场记录主键
     * @return 车辆进场记录
     */
    @Override
    public ParkingRecordIn selectParkingRecordInById(String id)
    {
        return parkingRecordInMapper.selectParkingRecordInById(id);
    }

    /**
     * 查询车辆进场记录列表
     * 
     * @param parkingRecordIn 车辆进场记录
     * @return 车辆进场记录
     */
    @Override
    @DataScope(deptAlias = "pri")
    public List<ParkingRecordIn> selectParkingRecordInList(ParkingRecordIn parkingRecordIn)
    {
        return parkingRecordInMapper.selectParkingRecordInList(parkingRecordIn);
    }

    /**
     * 新增车辆进场记录
     * 
     * @param parkingRecordIn 车辆进场记录
     * @return 结果
     */
    @Override
    public int insertParkingRecordIn(ParkingRecordIn parkingRecordIn)
    {
        return parkingRecordInMapper.insertParkingRecordIn(parkingRecordIn);
    }

    /**
     * 修改车辆进场记录
     * 
     * @param parkingRecordIn 车辆进场记录
     * @return 结果
     */
    @Override
    @Transactional
    public Boolean updateParkingRecordIn(ParkingRecordIn parkingRecordIn)
    {
        ParkingRecordInCorrectRequest parkingRecordInCorrectRequest = new ParkingRecordInCorrectRequest();
        String platformId =parkingRecordIn.getPlatformId();
        parkingRecordInCorrectRequest.setPlatformId(parkingRecordIn.getPlatformId());
        parkingRecordInCorrectRequest.setRecordId(parkingRecordIn.getRecordId());
        parkingRecordInCorrectRequest.setCarNum(parkingRecordIn.getCarNum());
        //若依通过字典值获取颜色
        String carNumColor = DictUtils.getDictLabel("car_num_color", String.valueOf(parkingRecordIn.getCarNumColor()));
        parkingRecordInCorrectRequest.setCarNumColor(carNumColor);
        parkingRecordInCorrectRequest.setIsParkingCloudSyncDown(1);
        parkingRecordInCorrectRequest.setCarInTime(DateUtils.localDateTimeToStr(parkingRecordIn.getCarInTime()));
        // 组装请求
        RequestData<ParkingRecordInCorrectRequest> requestData = new RequestData<>(
                MasWebsocketEnum.PARKING_CAR_RECHECK.getMethod(), parkingRecordInCorrectRequest);
        CommonRequest<ParkingRecordInCorrectRequest> request = new CommonRequest<>("transform", 1, requestData);
        log.info("在停车辆矫正请求JSON：{}", parkingRecordInCorrectRequest);
        try {
            Boolean result = webSocketMessageService.operationDevice(platformId, request);
            if (result) {
                log.info("车辆矫正成功");
                parkingRecordInMapper.updateParkingRecordIn(parkingRecordIn);
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("车辆矫正执行异常");
        }
    }

    /**
     * 批量删除车辆进场记录
     * 
     * @param ids 需要删除的车辆进场记录主键
     * @return 结果
     */
    @Override
    public int deleteParkingRecordInByIds(String[] ids)
    {
        return parkingRecordInMapper.deleteParkingRecordInByIds(ids);
    }

    /**
     * 删除车辆进场记录信息
     * 
     * @param id 车辆进场记录主键
     * @return 结果
     */
    @Override
    public int deleteParkingRecordInById(String id)
    {
        return parkingRecordInMapper.deleteParkingRecordInById(id);
    }

    @Override
    public Boolean openGateById(String id) {
        ParkingRecordIn parkingRecordIn = parkingRecordInMapper.selectParkingRecordInById(id);
        Optional.ofNullable(parkingRecordIn).orElseThrow(() -> new RuntimeException("无效的请求信息"));
        // 组装请求参数
        OpenGateRequest openGateRequest = new OpenGateRequest();
        openGateRequest.setPlatformId(parkingRecordIn.getPlatformId());
        openGateRequest.setParkingLotCode(parkingRecordIn.getParkingLotCode());
        openGateRequest.setLaneCode("1@X1Y1");
        openGateRequest.setCarNum(parkingRecordIn.getCarNum());
        return sendOpenGateRequest(openGateRequest);
    }

    @Override
    public Boolean openGateBySerialNumber(String serialNumber) {
        ParkingOrder parkingOrder = new ParkingOrder();
        parkingOrder.setOrderNo(serialNumber);
        ParkingOrder order = parkingOrderMapper.selectParkingOrder(parkingOrder);
        Optional.ofNullable(order).orElseThrow(() -> new RuntimeException("无效的请求信息"));
        // 组装请求参数
        OpenGateRequest openGateRequest = new OpenGateRequest();
        openGateRequest.setPlatformId(order.getPlatformId());
        openGateRequest.setParkingLotCode(order.getParkCode());
        openGateRequest.setLaneCode("1@X1Y1");
        openGateRequest.setCarNum(order.getCarNum());
        return sendOpenGateRequest(openGateRequest);
    }

    public Boolean sendOpenGateRequest(OpenGateRequest openGateRequest){
        openGateRequest.setOperatorName(getUsername());
        RequestData<OpenGateRequest> requestData = new RequestData<>(
                MasWebsocketEnum.REMOTE_OPEN_GATE.getMethod(), openGateRequest);
        CommonRequest<OpenGateRequest> openRequest = new CommonRequest<>("transform", 1, requestData);
        log.info("远程开闸请求JSON：{}", openGateRequest);
        try {
            Boolean result = webSocketMessageService.operationDevice(openGateRequest.getPlatformId(), openRequest);
            log.info("远程开闸结果: {}", result);
            if (result){ // 增加远程开闸记录
                ParkingRecordGate parkingRecordGate = new ParkingRecordGate();
                parkingRecordGate.setItcDevCode(openGateRequest.getItcDevCode());
                parkingRecordGate.setSluiceDevCode(openGateRequest.getSluiceDevCode());
                parkingRecordGate.setLaneCode(openGateRequest.getLaneCode());
                parkingRecordGate.setCarNum(openGateRequest.getCarNum());
                parkingRecordGate.setCreateBy(openGateRequest.getOperatorName());
                parkingRecordGate.setCreateTime(DateUtils.getNowDate());
                parkingRecordGateMapper.insertParkingRecordGate(parkingRecordGate);
            }
            return result;
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("未识别到出场车牌号");
        }
    }
}
